package com.huluobo.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.io.File
import java.lang.Exception

/**
 *  Created by LC on 2025/6/12.
 */
abstract class BaseViewModel<uiIntent : UIIntent> : ViewModel() {
    private val _uiIntent = Channel<UIIntent> { Channel.UNLIMITED }

    private var _state = MutableStateFlow<UIState>(UIState.OnLoading)
    val state: StateFlow<UIState>
        get() = _state

    init {
        viewModelScope.launch {
            _uiIntent.receiveAsFlow().collect {
                handleIntent(it)
            }
        }
    }

    abstract fun handleIntent(it: UIIntent)

    fun sendIntent(intent: UIIntent) {
        viewModelScope.launch {
            _uiIntent.send(intent)
        }
    }

    fun httpRequest(request: Flow<Res<Any>>, type: StateType = StateType.DEFAULT) {
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    ToastUtils.showLong("网络请求错误:${it.message}")
                    Log.e("TagA", "网络请求错误:${it.message}")
                }.collect {
                    if (it.code == 0) {
                        _state.value = UIState.OnSuccess(it.data, type)
                    } else {
                        _state.value = UIState.OnError(it.msg)
                    }
                }
        }
    }

    fun download(url: String, file: File) {
        viewModelScope.launch {
            DownloadUtils.download(url, file)
                .flowOn(Dispatchers.IO)
                .catch {
                    Log.e("TagA", "下载错误:${it.message}")
                }.collect {
                    _state.value = it
                }
        }
    }

    fun roomRequest(request: Flow<Any>, type: StateType = StateType.REGISTER) {
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.e("TagA", "数据库错误:${it.message}")
                }.collect {
                    if (it != null) {
                        _state.value = UIState.OnSuccess(it, type)
                    } else {
                        _state.value = UIState.OnError("数据库查询错误,数据为空")
                    }
                }
        }
    }

    fun scanFile(file: File) {
        viewModelScope.launch {
            try {
                val files = file.listFiles()

                val list = mutableListOf<LocalEntity>()
                for (i in files) {
                    list.add(LocalEntity(i.name, i.absolutePath))
                }
                _state.value = UIState.OnSuccess(list)

            } catch (e: Exception) {
                _state.value = UIState.OnError(e.message.toString())
            }
        }
    }
}

data class LocalEntity(val fileName: String, val flePath: String)